package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration =configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        //生成select mappedStatement
        List<Element> selectList = rootElement.selectNodes("//select");
        generateMappedStatement(selectList,namespace,SqlCommandType.SELECT);

        //生成insert mappedStatement
        List<Element> insertList = rootElement.selectNodes("//insert");
        generateMappedStatement(insertList,namespace,SqlCommandType.INSERT);

        //生成update mappedStatement
        List<Element> updateList = rootElement.selectNodes("//update");
        generateMappedStatement(updateList,namespace,SqlCommandType.UPDATE);


        //生成delete mappedStatement
        List<Element> deleteList = rootElement.selectNodes("//delete");
        generateMappedStatement(deleteList,namespace,SqlCommandType.DELETE);

    }

    private void generateMappedStatement(List<Element> list,String namespace,SqlCommandType sqlCommandType){
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setparameterType(parameterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlCommandType(sqlCommandType);
            String key = namespace+"."+id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }
    }
}
